package org.ucas.faker.web.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.ucas.faker.web.dao.DepotDao;
import org.ucas.faker.web.dao.TaskDao;
import org.ucas.faker.web.entity.Query;
import org.ucas.faker.web.entity.TaskLog;
import org.ucas.faker.web.exceptions.InternalServerException;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class TaskService {

  @Autowired
  private TaskDao taskDao;

  @Autowired
  private DepotDao depotDao;

  public TaskLog create(TaskLog task) {
    if(task.getId() != null || task.getOperator() == null || (task.getDepotId() != null &&
        taskDao.findByDepotIdAndVersionAndCategory(task.getDepotId(),task.getVersion(),task.getCategory()) != null))
      throw InternalServerException.INVALID_TASK_INFO;

    return taskDao.save(task);
  }

  public TaskLog persist(TaskLog task) {
    return taskDao.save(task);
  }

  public TaskLog load(long taskId) {
    return taskDao.findOne(taskId);
  }

  public TaskLog load(long depotId, long version, TaskLog.TaskCategory category) {
    return taskDao.findByDepotIdAndVersionAndCategory(depotId,version,category);
  }

  public TaskLog latest(long depotId, TaskLog.TaskCategory category) {
    PageRequest request = new PageRequest(0,1);
    Page<TaskLog> page = taskDao.history(depotId,category,request);
    return page.getTotalElements() == 0 ? null : page.getContent().get(0);
  }

  public void updateStatus(long taskId, TaskLog.TaskStatus status, Integer progress) {
    if(progress == null) taskDao.updateStatus(taskId, status);
    else taskDao.updateStatus(taskId,status,progress);
  }

  public TaskLog.TaskStatus status(long taskId) {
    return taskDao.queryStatus(taskId);
  }


  public void delete(long taskId) {
    taskDao.delete(taskId);
  }
}
